package com.yue92.datalife.exception;

import com.yue92.datalife.response.ResponseResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.stream.Collectors;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(UncheckedException.class)
    public ResponseResource<?> unchecked(UncheckedException exception) {
        return exception.getResult();
    }

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseResource<?> missing(MissingServletRequestParameterException exception) {
        return ResponseResource.failure(exception.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResource<?> notValid(MethodArgumentNotValidException exception) {
        List<ObjectError> objectErrors = exception.getBindingResult().getAllErrors();
        String message = objectErrors.stream().map(o -> {
            String[] codes = o.getCodes();
            if (codes == null) {
                return o.getDefaultMessage();
            } else {
                return codes[0] + o.getDefaultMessage();
            }
        }).collect(Collectors.joining( "; " ));
        return ResponseResource.failure(message);
    }

    @ExceptionHandler(Exception.class)
    public ResponseResource<?> defaultHandler(Exception exception) {
        log.error("defaultHandler", exception);
        return ResponseResource.failure(exception.getMessage());
    }
}
